#连续站上均线特征计算

import numpy as np
import pandas as pd
from Utils.DataLoaderAndSaver import DataLoaderAndSaver
from Utils.configs import daysBefore1, daysBefore2, yearsBefore


class MaFeatureCalculation:
    def __init__(self,daysBefore1=0,daysBefore2=1,yearsBefore=4):
        #基本的配置信息
        self.maDays=[5,10,20,30,40,50,60,70,80,90,100,120,122,150,180,200,244,250,300]
        self.maTable='table_mas'
        self.dataLoaderAndSaver=DataLoaderAndSaver(daysBefore1=daysBefore1,daysBefore2=daysBefore2,yearsBefore=yearsBefore)
        self.codes=self.dataLoaderAndSaver.allstocks.index
        self.dailyprices=self.dataLoaderAndSaver.dailyprices

    #计算历史的MA均线
    def calMas(self):
        #先删除历史表格，再重新写入
        try:
            self.dataLoaderAndSaver.dropTable(self.maTable)
        except:
            print('正常删除表格%s'%self.maTable)
        for code in self.codes:
            try:
                prices = self.dailyprices[self.dailyprices['code'] == code]
                prices=prices[prices['close']!=np.nan]
                print(prices.shape,prices.head(10))
                index=prices['date']
                # print(prices.index)
                close=pd.DataFrame(prices['close'])
                close.index=index
                mas=[close]
                for day in self.maDays:
                    ma=pd.DataFrame(prices['close'].rolling(window=day).mean())
                    ma.columns=['ma_'+str(day)]
                    ma.index=index
                    print('ma_'+str(day),ma.tail(5))
                    mas.append(ma)
                df=pd.concat(mas,axis=1)
                df.insert(0,'code',code)
                df.insert(0,'date',df.index)
                # df.colums=self.maColumns
                # df=df.dropna()
                print(df.columns, df.shape,df.head(10))
                # df.columns=self.maColumns
                print(df.columns,df.shape)
                self.dataLoaderAndSaver.saveData(self.maTable,df,if_exists='append')
            except:
                print(code, '计算失败')
                with open('log/'+self.dataLoaderAndSaver.todayDate + '_ma_fail.txt', 'a+', encoding='utf8') as f:
                    f.write(code + '\n')
                continue


mafc=MaFeatureCalculation(daysBefore1=daysBefore1,daysBefore2=daysBefore2,yearsBefore=yearsBefore)
mafc.calMas()